<?php
/**
 * @author hjj
 * 洋葱供应商地区编码
 */
namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use App\Service\Code\Normal;
use App\Service\BaseService;

class ShoponionArea extends BasePssModel {

    public $table = 'shoponion_area';

    const REDIS_KEY = 'REDIS_SHOPONION_AREA_KEY';

    /**
     * 获取区域对应的编码
     * @param array $regions
     */
    public function getAreaCode($regions = []) {
        $redis      = BaseService::instance()->getRedisObj();
        $this->getAreaCodeByCache($redis);
        if( in_array($regions['province'],[
            '重庆市',
            '北京市',
            '上海市',
            '天津市'
        ])) {
            $regions['province'] = str_replace("市","", $regions['province']);
        }
        
        //省
        $provinceInfo = $redis->hget(self::REDIS_KEY, $regions['province']);
        if (empty($provinceInfo)) {
            return Normal::returnCode(Normal::FAIL, "获取洋葱收货地址省份编码异常，请联系管理员");
        }
        $provinceInfo = json_decode($provinceInfo, true);

        //市
        $cityList = array_column($provinceInfo['list'], null, 'name');
        if (empty($cityList[$regions['city']])) {
            return Normal::returnCode(Normal::FAIL, "获取洋葱收货地址市编码异常，请联系管理员");
        }
        $cityInfo = $cityList[$regions['city']];

        //区
        $districtInfo = array_column($cityInfo['list'], null, 'name');
        if (empty($districtInfo[$regions['district']])) {
            return Normal::returnCode(Normal::FAIL, "获取洋葱收货地址区县编码异常，请联系管理员");
        }
        $districtInfo = $districtInfo[$regions['district']];
        return Normal::returnCode(Normal::SUC, "获取成功", [
            'provinceCode' => $provinceInfo['id'],
            'cityCode'     => $cityInfo['id'],
            'districtCode' => $districtInfo['id'],
        ]);
    }

    /**
     * set redis cache
     */
    public function getAreaCodeByCache($redis) {
        if ($redis->hlen(self::REDIS_KEY) > 0) {
            return Normal::returnCode(Normal::SUC, "获取成功");
        }
        $list = self::instance()->rows([['pid','>',0]]);
        if (empty($list)) {
            return Normal::returnCode(Normal::FAIL, "省市区编码映射表为空");
        }
        $listTree = tree($list, 100000, 'id', 'pid');
        foreach ($listTree as $tree) {
            $redis->hset(self::REDIS_KEY, $tree['name'], json_encode($tree, JSON_UNESCAPED_UNICODE));
        }
        return Normal::returnCode(Normal::SUC, "设置成功");
    }
}